<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 11:06
 */

namespace app\manage\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;

// 引入ZBuilder
use app\common\model\Work as WorkModel;
use app\common\model\WorkNum as WorkNumModel;
use think\Db;

class Work extends Admin
{
    //新闻分类列表
    public function lists( )
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('qt_work')
            ->alias('w')
            ->leftJoin('qt_store s','w.store_id = s.id')
            ->field('w.*,s.name as title')
            ->where($map)
            ->order('id desc')
            ->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '编辑考勤',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('edit', ['id' => '__id__']),
        ];
        $btn_access2 = [
            'title' => '删除考勤',
            'icon' => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href' => url('delete', ['id' => '__id__']),
        ];
        $btn_access3 = [
            'title' => '新增考勤',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-info',
            'href' => url('add'),
        ];
        $btn_access4 = [
            'title' => '设置打卡时间',
            'icon' => 'fa fa-fw fa-th-list',
            'class' => 'btn btn-xs btn-default',
            'href' => url('son_list', ['id' => '__id__']),
        ];
        $news_category = Db::name('qt_daily_type')->column('id,name');
        $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
        $news_category['0'] = '顶级分类';
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '班次名称', 'text')
            ->addColumn('title', '所属门店', 'text')
            ->addColumn('work_rule', '考勤规则', 'text')
            ->addColumn('repair_rule', '补卡规则', 'text')
            ->addColumn('repair_num', '补卡次数', 'text')
            ->addColumn('status', '状态', 'status', '', ['1' => '显示', '2' => '隐藏'])
            ->addColumn('created_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s')
            ->addColumn('right_button', '操作', 'btn')
            ->setSearchArea([
                ['select:2', 'w.post_id', '所属岗位', 'eq', '', $post_category],
                ['text:2', 'w.name', '考勤班次', 'like'],
            ])
            ->addTopButton('single', $btn_access3) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->addRightButton('delete', $btn_access2) // 添加右侧按钮
            ->addRightButton('list', $btn_access4) //
            ->setPrimaryKey('id') // 设置主键名为username
            ->setColumnWidth([
                'id'  => 30,
                'status' => 40,
                'repair_num'=>50,
                'work_num'=>50,
                'right_button'=>50,
                'name'=>100,
                'title'=>60
            ])
            ->setPageTitle('考勤班次')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }

    //添加考勤打卡
    public function add( )
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'Work.add');
            if (true !== $result) $this->error($result);
            $data['created_time'] = time();
            if (WorkModel::create($data)) {
                $this->success('新增成功', url('lists'));
            } else {
                $this->error('新增失败');
            }
        } else {
            $post_category = Db::name('qt_post')->order('id asc')->column('id,title');
            $storeRes = Db::name('qt_store')->where('status','1')->column('id,name');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['text:7', 'name', '考勤名称'],
                        ['select:7','store_id','所属门店','<code>请选择所属门店</code>',$storeRes],
                        ['text:7', 'time_rule', '上班时间说明','<code>示例：周一到周五9:00-18:00，周六日休息</code>'],
                        ['text:7', 'work_rule', '考勤规则说明','<code>示例：第一天下班晚走两个小时，第二天可以晚来一个小时</code>'],
                        ['text:7', 'repair_rule', '补卡规则说明','<code>示例：每个月最多3次补卡机会，可以补半个月内的缺卡</code>'],
                        ['text:7', 'repair_time', '补卡时间','<code>单位：天</code>'],
                        ['text:7', 'repair_num', '每月补卡次数','<code>补卡次数</code>'],
                        ['text:7', 'late', '允许迟到时间','<code>允许迟到时间，单位：分</code>'],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏'], '1'],
                    ]
                )
                ->setPageTitle('新增考勤设置')
                ->fetch();
        }
    }
    //编辑考勤打卡
    public function edit($id = null)
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            // 验证
            $result = $this->validate($data, 'Work.add');
            //if (true !== $result) $this->error($result);
            if (WorkModel::update($data)) {
                $this->success('编辑成功', 'lists');
            } else {
                $this->error('编辑失败');
            }
        } else {
            $info = WorkModel::get($id);
            $groupRes = Db::name('qt_group')->whereIn('pid', ['0','1'])->column('id,name');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden', 'id', 'id'],
                        ['text:7', 'name', '考勤名称'],
                        ['select:7','group_id','所属团队','<code>请选择所属团队</code>',$groupRes],
                        ['text:7', 'time_rule', '上班时间说明','<code>示例：周一到周五9:00-18:00，周六日休息</code>'],
                        ['text:7', 'work_rule', '考勤规则说明','<code>示例：第一天下班晚走两个小时，第二天可以晚来一个小时</code>'],
                        ['text:7', 'repair_rule', '补卡规则说明','<code>示例：每个月最多3次补卡机会，可以补半个月内的缺卡</code>'],
                        ['text:7', 'repair_time', '补卡时间','<code>单位：天</code>'],
                        ['text:7', 'repair_num', '每月补卡次数','<code>补卡次数</code>'],
                        ['text:7', 'late', '允许迟到时间','<code>允许迟到时间，单位：分</code>'],
                        ['radio:7', 'work_num', '每日打卡次数','',['2' => '2次', '4' => '4次','6' => '6次', '8' => '8次']],
                        ['radio:', 'status', '状态', '', ['1' => '显示', '2' => '隐藏']],
                    ]
                )
                ->setFormData($info)
                ->setPageTitle('编辑考勤设置')
                ->fetch();
        }
    }

    //删除新闻分类
    public function delete($id = null)
    {
        if ($id === null) $this->error('缺少参数');
        $son = Db::name('qt_work_num')->where('work_id', $id)->count();
        if ($son > 0) {
            $this->error('请先删除下属分类', 'lists');
        }
        $re = WorkModel::destroy($id);// 删除主键为1,2,3的数据
        if ($re) {
            $this->success('删除成功', 'lists');
        } else {
            $this->error('系统繁忙请稍后再试', 'lists');
        }

    }

    //打卡时间列表
    public function son_list($id = '' )
    {
        // 读取数据
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('qt_work_num')
            ->alias('wn')
            ->field('wn.*,w.name as work_name')
            ->leftJoin('qt_work w', 'w.id = wn.work_id')
            ->where($map)
            ->where('wn.work_id',$id)
            ->order('wn.id desc')
            ->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '编辑打卡时间',
            'icon' => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href' => url('son_edit', ['id' => '__id__','work_id'=>$id]),
        ];
        $btn_access = [
            'title' => '新增打卡时间',
            'icon' => 'fa fa-fw fa-plus',
            'class' => 'btn btn-success',
            'href' => url('son_add',['id'=>$id]),
        ];
        $btn_access2 = [
            'title' => '删除打卡时间',
            'icon' => 'fa fa-fw fa-trash-o',
            'class' => 'btn btn-xs btn-default ajax-get confirm',
            'href' => url('son_delete', ['work_id'=>$id,'id' => '__id__']),
        ];
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('work_name', '考勤名称', 'text')
            ->addColumn('start_time', '开始时间', 'text')
            ->addColumn('end_time', '结束时间', 'text')
            ->addColumn('week', '星期', 'status', '', ['1' => '星期一', '2' => '星期二','3' => '星期三', '4' => '星期四','5' => '星期五', '6' => '星期六','7'=>'星期日'])
            ->addColumn('type', '类型', 'status', '', ['1' => '工作日', '2' => '休息日'])
            ->addColumn('right_button', '操作', 'btn')
//            ->setSearchArea([
//                ['select:2', 'da.post_id', '所属岗位', 'eq', '', $post_category],
//                ['text:2', 'da.name', '分类名称', 'like'],
//            ])
            ->addTopButton('custom', $btn_access) // 添加顶部按钮
            ->addRightButton('edit', $btn_access1) // 添加右侧按钮
            ->addRightButton('delete', $btn_access2) // 添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名为username
            ->setPageTitle('考勤时间列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }


    //添加日报审批分类
    public function son_add($id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $result = $this->validate($data, 'Work.son_add');
            if (true !== $result) $this->error($result);
            $insert = [];
            foreach ($data['week'] as $key=>$value){
                $insert[$key]['work_id'] = $id;
                $insert[$key]['start_time'] = $data['start_time'];
                $insert[$key]['end_time'] = $data['end_time'];
                $insert[$key]['week'] = $value;
                $insert[$key]['created_time'] = time();
            }
            $res = Db::name('qt_work_num')->insertAll($insert);
            if ($res) {
                $this->success('新增成功', url('son_list',['id'=>$id]));
            } else {
                $this->error('新增失败');
            }
        } else {
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['time:7', 'start_time', '开始时间','','','HH:mm'],
                        ['time:7', 'end_time', '结束时间','','','HH:mm'],
                        ['checkbox:7', 'week', '时间', '',  ['1' => '星期一', '2' => '星期二','3' => '星期三', '4' => '星期四','5' => '星期五', '6' => '星期六','7'=>'星期日']],
                        ['radio:7','type','类型','',['1'=>'工作日','2'=>'休息日'],'1'],
                    ]
                )
                ->setPageTitle('新增时间')
                ->fetch();
        }
    }



    //修改日报二级分类
    public function son_edit($id = '',$work_id = '')
    {
        //判断是否提交信息
        if ($this->request->isPost()) {
            //$info = WorkNumModel::get($id);
            // 表单数据
            $data = $this->request->post();
            if (WorkNumModel::where('id',$id)->update($data)) {
                $this->success('修改成功', url('son_list',['id'=>$work_id]));
            } else {
                $this->error('修改失败');
            }
        } else {
            $info = WorkNumModel::get($id);
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id',$id],
                        ['time:7', 'start_time', '开始时间','','','HH:mm'],
                        ['time:7', 'end_time', '结束时间','','','HH:mm'],
                        //['checkbox:7', 'week', '时间', '',  ['1' => '星期一', '2' => '星期二','3' => '星期三', '4' => '星期四','5' => '星期五', '6' => '星期六','7'=>'星期日']],
                        ['radio:7','type','类型','',['1'=>'工作日','2'=>'休息日']],
                    ]
                )
                ->setPageTitle('修改打卡时间')
                ->setFormData($info)
                ->fetch();
        }
    }



    //删除二级分类
    public function son_delete($id = null,$work_id  = '')
    {
        if ($id === null) $this->error('缺少参数');
        $re = WorkNumModel::destroy($id);// 删除主键为1,2,3的数据
        if ($re) {
            $this->success('删除成功', url('son_list',['id'=>$work_id]));
        } else {
            $this->error('系统繁忙请稍后再试', url('son_list',['id'=>$work_id]));
        }

    }


    /**
     * 获取当前团队下面的岗位
     * @param $team_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function get_post($group_id){
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $data= Db::name('qt_post')->where('team_id',$group_id)->field('id,title')->select(); //数据
        $result = [];
        foreach ($data as $key=>$value){
            $result[$key]['key'] = $value['id'];
            $result[$key]['value'] = $value['title'];
        }
        $arr['list'] = $result;
        return json($arr);
    }


}